package com.hzw.net.utils

import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ProcessLifecycleOwner

/**
 *
 * @Author:         HuaZhongWei
 * @CreateDate:     2020/11/10 16:46
 *
 * @Description:    进程状态监听
 *
 */
object AppProcessObserver {

    private var create: (() -> Unit)? = null
    private var start: (() -> Unit)? = null
    private var resume: (() -> Unit)? = null
    private var pause: (() -> Unit)? = null
    private var stop: (() -> Unit)? = null

    private var observer = object : DefaultLifecycleObserver {
        override fun onCreate(owner: LifecycleOwner) {
            //只会调用一次
            create?.invoke()
        }

        override fun onStart(owner: LifecycleOwner) {
            //进入前台
            start?.invoke()
        }

        override fun onResume(owner: LifecycleOwner) {
            resume?.invoke()
        }

        override fun onPause(owner: LifecycleOwner) {
            pause?.invoke()
        }


        override fun onStop(owner: LifecycleOwner) {
            // 进入后台
            stop?.invoke()
        }

        override fun onDestroy(owner: LifecycleOwner) {
            // 不会调用
        }
    }

    /**
     * 监听App前后台状态
     * 注：只能在application中进行注册
     */
    fun register(foreground: (() -> Unit)? = null, background: (() -> Unit)? = null) {
        start = foreground
        stop = background
        ProcessLifecycleOwner.get().lifecycle.addObserver(observer)
    }

    /**
     * 监听App进程所有状态
     * 注：只能在application中进行注册
     */
    fun register(
        crate: (() -> Unit)? = null,
        start: (() -> Unit)? = null,
        resume: (() -> Unit)? = null,
        pause: (() -> Unit)? = null,
        stop: (() -> Unit)? = null
    ) {
        create = crate
        AppProcessObserver.start = start
        AppProcessObserver.resume = resume
        AppProcessObserver.pause = pause
        AppProcessObserver.stop = stop
        ProcessLifecycleOwner.get().lifecycle.addObserver(observer)
    }
}